<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\wxBizDataCrypt;
use app\model\Admin;
use app\model\AuthRule;
use app\model\WxUsers;
use think\exception\ValidateException;
use app\validate\Login as ValidateLogin;
use think\facade\Config;
use think\Request;

class Login extends BaseController
{

    /**
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 11:45
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 用户登录
     */
    public function doLogin()
    {
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        try {
            $this->validate(['mobile' => $mobile, 'password' => $password], ValidateLogin::class);
            if (!$admin = Admin::where('mobile', $mobile)->find()) {
                return $this->response(403, '用户名不存在');
            }
            if (!password_verify($password, $admin->password)) {
                return $this->response(403, '密码错误');
            }
            $token = $this->token->createToken($admin->id);
            $admin->token = $token;
            $admin->login_status = 1; //登录
            $admin->save();

        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
        return $this->response($admin->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/7/22
     * @Time: 16:01
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取admin管理员信息
     */
    public function adminShow()
    {
        $admin = Admin::find($this->request->uid);
        if (is_null($admin)) {
            return $this->response(404, '此用户不存在');
        }
        // 检查用户权限
        $role_ids = array_column($admin->roles()->select()->toArray(),
            'rules');//获取该用户所属角色rules
        $where = [];
        if (!in_array('*', $role_ids)) {
            //->where('is_open', AuthRule::OPEN_ONE)
            $where[] = array('id', 'in', implode(',', $role_ids));
        }
        $data = AuthRule::field('id,name')->where($where)->select()->toArray();

        $url = [];
        foreach ($data as $key => $v) {
            $url[] = $v['name'];
        }
        $user['url'] = implode(',', $url);
        $user['role'] = implode(',', $role_ids);
        return $this->response($user);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/2
     * @Time: 9:10
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 授权登录
     */
    public function wxLogin()
    {
        $data = $this->request->param();
        $res = \app\model\WxUsers::find($this->request->wx_user_id);
        if (is_null($res)) {
            return $this->response(500, '未找到相关信息');
        }
        $res->save($data);
        return $this->response($res->toArray());

    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/17
     * @Time: 12:45
     * @return \think\response\Json
     * 验证
     */
    public function verifyUser()
    {
        $user = \app\model\WxUsers::find($this->request->wx_user_id);
        if (is_null($user)) {
            return $this->response(403, '找不到该用户');
        }
        if (empty($user->mobile)) {
            return $this->response(403, '手机号为空');
        }
        return $this->response();
    }

    //微信获取appid
    public function getXcxToken()
    {
        $code = $this->request->param('code');
        $wx_url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . Config::get('wechat.wx.app_id') . "&secret=" . Config::get('wechat.wx.app_secret') . "&js_code=" . $code . "&grant_type=" . Config::get('wechat.wx.grant_type') . "";
        $wx_data = $this->http($wx_url, 'get');
        if ($wx_data[0] == 200) {
            $wxResult = json_decode($wx_data[1], TRUE);
            //判空
            if (empty($wxResult)) {
                return $this->response(500, '获取session_key,openID时异常，微信内部错误');
            } else {
                //判断返回的结果中是否有错误码
                if (isset($wxResult['errcode'])) {
                    //如果有错误码，调用抛出错误方法
                    return $this->response(500, $wxResult);
                } else {
                    //1.通过openid 查看用户是否存在
                    $user = \app\model\WxUsers::where('openid', $wxResult['openid'])->find();
                    //2判断用户是否存在
                    if (!is_null($user)) {
                        $uid = $user['id'];
                    } else {
                        //如果为空 把openid数据库插入一条
                        $new_user_id = \app\model\WxUsers::create(['username' => '', 'openid' => $wxResult['openid'], 'session_key' => $wxResult['session_key']])->id;
                        $uid = $new_user_id;
                    }
                }

            }
            $key = $this->token->createToken($uid);//生成token
            return $this->response(['token' => $key]);
        } else {
            return $this->response(500, '连接微信服务器失败');
        }
    }

    /**、
     * @User: 刘海龙
     * @Date: 2021/7/7
     * @Time: 16:02
     * @return \think\response\Json
     * 验证
     */
    public function tokenVerify()
    {
        $token = $this->request->param('token');
        if (!$token) {
            return $this->response(500, 'token不允许为空');
        }
        $valid = $this->verifyToken($token);
        $arr = ['isValid' => $valid];
        return json($arr);
    }

    //验证Token
    public function verifyToken($token)
    {
        $exist = $this->token->checkTokenJWT($token);
        if ($exist['code'] === 10000) {
            return true;
        } else {
            return false;
        }
    }
}
